package com.laoli.lab38;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * anyOf()示例：多元OR聚合
 */
public class AnyOfDemo {

    public static void main(String[] args) throws InterruptedException {
        // 问：任务A、任务B、任务C各出一个随机数(1-100)，任务D计算这三个随机数的和？
        // 关键：任务A、任务B、任务C、任务D都是异步任务

        // 异步任务A
        CompletableFuture<Integer> taskA = CompletableFuture.supplyAsync(() -> {
            Integer rndA = new Random().nextInt(100) + 1;
            System.out.println("rndA = " + rndA);
            try {
                Thread.sleep(300);//休眠300ms
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return rndA;
        });  // 300ms
        // 异步任务B
        CompletableFuture<Integer> taskB = CompletableFuture.supplyAsync(() -> {
            Integer rndB = new Random().nextInt(100) + 1;
            System.out.println("rndB = " + rndB);
            try {
                Thread.sleep(200);//休眠200ms
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return rndB;
        }); // 200ms
        // 异步任务C
        CompletableFuture<Integer> taskC = CompletableFuture.supplyAsync(() -> {
            Integer rndC = new Random().nextInt(100) + 1;
            System.out.println("*rndC = " + rndC);
            try {
                Thread.sleep(100);//休眠100ms
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return rndC;
        }); // 100ms

        // 异步任务D(获取任务A、B、C之中最快出的结果)
        CompletableFuture<Object> taskD = CompletableFuture.anyOf(taskA, taskB, taskC);
        taskD.thenAccept(result -> {
            // 消费结果(输出)
            System.out.println("result = " + result);
        });

        Thread.sleep(500);
    }
}
